package com.zr.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zr.constant.MessageConstant;
import com.zr.constant.RedisConstant;
import com.zr.entity.PageResult;
import com.zr.entity.QueryPageBean;
import com.zr.entity.Result;
import com.zr.pojo.Setmeal;
import com.zr.service.SetmealService;
import com.zr.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

/**
 * @auther zhaorui
 * @date 2019-11-25 - 16:38
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {


    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;


    /**
     * 图片上传
     * @param imgFile
     * @return
     */
    @RequestMapping("/upload")
    //@RequestParam;  如果名称和表单中的name相同 则不需要 @RequestParam
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        //
        String originalFilename = imgFile.getOriginalFilename();//原始文件名
        int index = originalFilename.lastIndexOf(".");//拿到最后一个点的索引
        String suffix = originalFilename.substring(index - 1);//从index-1开始截取 得到.jpg
        UUID uuid = UUID.randomUUID(); //UUID 获取随机不重复的文件名
        String filename = uuid + suffix; //组成新的文件名
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),filename); //上传
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,filename);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(MessageConstant.PIC_UPLOAD_FAIL);
        }
        return Result.ok(MessageConstant.PIC_UPLOAD_SUCCESS, filename);//将文件名返回 给前台

    }


    /**
     * 添加
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal , Integer[] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
            return Result.ok(MessageConstant.ADD_SETMEAL_SUCCESS,null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(MessageConstant.ADD_SETMEAL_FAIL);

        }

    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return  setmealService.QueryPage(queryPageBean);
    }
}
